// 拓展vue原有功能：全局组件、自定义指令、挂在原型方法
import defaultImg from '@/assets/images/200.png'
import Message from './Message'
import Confirm from './Confirm'

const importFn = require.context('./', false, /\.vue/)

export default {
  install(app) {
    // 注册全局组件
    importFn.keys().forEach(path => {
      const component = importFn(path).default
      app.component(component.name, component)
    })

    // 定义指令
    defineDirective(app)

    // 定义原型函数
    app.config.globalProperties.$message = Message
    app.config.globalProperties.$Confirm = Confirm
  }
}

// 图片懒加载指令
const defineDirective = (app) => {
  app.directive('lazy', {
    mounted(el, binding) {
      const observer = new IntersectionObserver(([{ isIntersecting }]) => {
        if (isIntersecting) {
          // 停止观察
          observer.unobserve(el)
          el.src = binding.value

          // 错误加载图片触发事件
          el.onerror = () => {
            el.src = defaultImg
          }
        }
      }, {
        threshold: 0
      })

      // 开启观察
      observer.observe(el)
    }
  })
}
